package com.taptech.doufu.ui.view.topicview;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.taptech.doufu.R;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.ui.activity.weex.SimpleWeexActivity;
import com.taptech.doufu.ui.adapter.DFMemberAdapter;
import com.taptech.doufu.ui.adapter.DfhomeNovelAdapter3;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.UmengEventName;
import com.taptech.doufu.bean.EventBean;
import com.taptech.doufu.bean.novel.VipAlbumBean;
import com.taptech.doufu.bean.novel.VipMixWorksBean;
import com.taptech.doufu.bean.novel.VipTopicBean;
import com.taptech.doufu.bean.novel.VipTopicGsonBean;
import com.taptech.doufu.constant.FragmentLoadType;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.event.EventBusLoginout;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.ui.view.topicview.adapter.VipNomalGridAdapter;
import com.taptech.doufu.util.StartActivityUtils;
import com.taptech.doufu.util.TMAnalysis;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2017/4/13/013.
 */
public class VipMixTopicView extends LinearLayout{
    private static final int TYPE_MORE = 1;
    private static final int TYPE_REPLACE = 2;

    private TextView tvTitle,tvMore;
    private RecyclerView rvContent;
    private LinearLayout llReplace;
    private View mtView;
    private String title;
    private String sexType;

    private int MAX_COUNT = 9;
    public VipMixTopicView(Context context) {
        super(context);
    }

    public VipMixTopicView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public VipMixTopicView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    private View root_layout;
    private View linearLayout0;
    private Context context;
    private View rl_dfnovel_layout1;
    private VipNomalGridAdapter contentAdapter;


    private LinearLayout llBtnOne,llBtnTwo,llBtnThree,llBtnFour,llBtnFive,llTop,llTop2;
    private TextView tvBtnOne,tvBtnTwo,tvBtnThree,tvBtnFour,tvBtnFive;

    private HashMap<String, List<VipMixWorksBean>> cache = new HashMap<>();
    private VipAlbumBean.AlbumInfo selectAlbumInfo;


    private List<VipMixWorksBean> simpleList;
    private List<VipAlbumBean> list;

    private String moreUrl ;

    private int type = 0;
    private int more ;  //more 0 1 2 没有 更多 换一批
    private boolean isHasTopTitle = false;
    private EventBean eventBean;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setVolumeKey(EventBusLoginout event){
        if (event != null&& event.getTag() !=null
                && event.getTag().equals(EventBusLoginout.tag)) {
            if (type == DFMemberAdapter.TYPE_MIX){
                resetData();
            }
        }
    }

    public VipMixTopicView(final Context context, final VipTopicBean model,String sexType){
        this(context);
        EventBus.getDefault().register(this);
        View view = LayoutInflater.from(context).inflate(R.layout.topic_vip_mix_view, null);
        this.context = context;
        this.sexType = sexType;
        linearLayout0 = view.findViewById(R.id.home_dfnovel_layout0);
        rl_dfnovel_layout1 = view.findViewById(R.id.rl_dfnovel_layout1);
        initTopUI(view,model);
        more = model.getMore();
        moreUrl = model.getMoreUrl();
        this.eventBean = model.getEventBean();
        initMore(view);
        llReplace.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                UmengEventUtil.addEvent(context,UmengEventName.VIP_CARD_RIGHT_TOP_BTN,eventBean);
                if (more == TYPE_REPLACE) {
                    replaceData();
                }else{  //更多
                    if (type == DFMemberAdapter.TYPE_NOMAL_COMMIC_DISCOUNT) {
                        Intent intent=new Intent();
                        intent.putExtra(Constant.URL,moreUrl);
                        intent.putExtra(FragmentLoadType.fragmentTypeName,model.getTitle());
                        intent.putExtra(FragmentLoadType.fragmentType,FragmentLoadType.RECOMMENDMORE);
                        new StartActivityUtils(context,intent).toCarttonSortDesActivity();
                    } else if (type == DFMemberAdapter.TYPE_CHAT_NOVEL_ALL_FREE) {
                        HashMap map = new HashMap();
                        map.put("title", model.getTitle());
                        map.put("moreUrl", model.getMoreUrl());
                        SimpleWeexActivity.startActivity(context,model.getWeexUrl(), map);
                    }else{
                        if(moreUrl!=null && moreUrl.contains("/weex/")){
                            SimpleWeexActivity.startActivity(context,moreUrl);
                        }else{
                            DfhomeNovelAdapter3.goToNovelMoreActivity(context,moreUrl,model.getTitle(),"");
                        }
                    }
                }

            }
        });
        mtView = view.findViewById(R.id.mtView);
        root_layout = view.findViewById(R.id.root_layout);
        tvTitle = (TextView) view.findViewById(R.id.tvTitle);
        rvContent = (RecyclerView) view.findViewById(R.id.rvContent);
        tvTitle.setText(model.getTitle());
        changeDayModelBg();
        if (list != null) {
            list.clear();
        }
        title = model.getTitle();
        list = model.getList();
        simpleList = model.getSimpleList();
        type = model.getModel();
        if (type == DFMemberAdapter.TYPE_VERTICAL) {
            mtView.setVisibility(GONE);
        }else{
            mtView.setVisibility(VISIBLE);
        }
        if (type == DFMemberAdapter.TYPE_MIX ||
                type == DFMemberAdapter.TYPE_NOMAL_NOVEL_DISCOUNT) {  //有头部
            if (list != null && list.size() > 0 && list.get(0)!=null) {
                setContent(list.get(0).getList());
                //设置缓存
                if (list.get(0).getAlbumInfo() != null) {
                    selectAlbumInfo = list.get(0).getAlbumInfo();
                    cache.put(list.get(0).getAlbumInfo().getName(), list.get(0).getList());
                }
            }
            isHasTopTitle = true;
        }else{  //无头部
            setContent(simpleList);
            isHasTopTitle = false;
        }
        addView(view);
    }

    private void resetData() {
        if (cache!=null){
            cache.clear();
        }
        replaceData();

    }

    private void initMore(View view) {
        llReplace = (LinearLayout) view.findViewById(R.id.llReplace);
        tvMore = (TextView) view.findViewById(R.id.tvMore);
        if (more == TYPE_MORE) { //更多
            llReplace.setVisibility(VISIBLE);
            tvMore.setText("更多");
        } else if (more == TYPE_REPLACE) {  //换一批
            llReplace.setVisibility(VISIBLE);
            tvMore.setText("换一批");
        }else{
            llReplace.setVisibility(GONE);
        }

    }



    private void initTopUI(View view,VipTopicBean model) {
        llTop = (LinearLayout) view.findViewById(R.id.llTop);
        llTop2 = (LinearLayout) view.findViewById(R.id.llTop2);
        llBtnOne = (LinearLayout) view.findViewById(R.id.llBtnOne);
        llBtnOne.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                TMAnalysis.event(context,UmengEventName.VIP_CARD_SWITCH_TAB);
                selectTopThreeSelect(0);
                switchData(list.get(0).getAlbumInfo());
            }
        });
        llBtnTwo = (LinearLayout) view.findViewById(R.id.llBtnTwo);
        llBtnTwo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                TMAnalysis.event(context,UmengEventName.VIP_CARD_SWITCH_TAB);
                selectTopThreeSelect(1);
                switchData(list.get(1).getAlbumInfo());

            }
        });
        llBtnThree = (LinearLayout) view.findViewById(R.id.llBtnThree);
        llBtnThree.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                TMAnalysis.event(context,UmengEventName.VIP_CARD_SWITCH_TAB);
                selectTopThreeSelect(2);
                switchData(list.get(2).getAlbumInfo());

            }
        });
        llBtnFour = (LinearLayout) view.findViewById(R.id.llBtnFour);
        llBtnFour.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                TMAnalysis.event(context,UmengEventName.VIP_CARD_SWITCH_TAB);
                selectTopTwoSelect(0);
                switchData(list.get(0).getAlbumInfo());

            }
        });
        llBtnFive = (LinearLayout) view.findViewById(R.id.llBtnFive);
        llBtnFive.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                TMAnalysis.event(context,UmengEventName.VIP_CARD_SWITCH_TAB);
                selectTopTwoSelect(1);
                switchData(list.get(1).getAlbumInfo());

            }
        });
        tvBtnOne = (TextView) view.findViewById(R.id.tvBtnOne);
        tvBtnTwo = (TextView) view.findViewById(R.id.tvBtnTwo);
        tvBtnThree = (TextView) view.findViewById(R.id.tvBtnThree);
        tvBtnFour = (TextView) view.findViewById(R.id.tvBtnFour);
        tvBtnFive = (TextView) view.findViewById(R.id.tvBtnFive);
        try {
            if ((model.getModel() == DFMemberAdapter.TYPE_MIX|| model.getModel() == DFMemberAdapter.TYPE_NOMAL_NOVEL_DISCOUNT) && model.getList().size()>1) {
                if (model.getList().size() == 2) {
                    llTop.setVisibility(GONE);
                    llTop2.setVisibility(VISIBLE);
                    tvBtnFour.setText(model.getList().get(0).getAlbumInfo().getName());
                    tvBtnFive.setText(model.getList().get(1).getAlbumInfo().getName());
                    selectTopTwoSelect(0);
                }else{

                    llTop2.setVisibility(GONE);
                    llTop.setVisibility(VISIBLE);
                    tvBtnOne.setSelected(true);

                    tvBtnOne.setText(model.getList().get(0).getAlbumInfo().getName());
                    tvBtnTwo.setText(model.getList().get(1).getAlbumInfo().getName());
                    tvBtnThree.setText(model.getList().get(2).getAlbumInfo().getName());
                    selectTopThreeSelect(0);
                }
            }else{
                llTop.setVisibility(GONE);
                llTop2.setVisibility(GONE);
            }
        } catch (Exception e) {
            llTop.setVisibility(GONE);
            llTop2.setVisibility(GONE);
        }
    }

    private void selectTopTwoSelect(int selectIndex) {
        if(WeMediaApplication.getInstance().isDayNightMode_Night){
            if (selectIndex == 0) {
                llBtnFour.setBackgroundResource(R.drawable.cycle_red_night);
                tvBtnFour.setTextColor(Color.parseColor("#ffffff"));

                llBtnFive.setBackgroundResource(R.drawable.bg_tag_gray_dark);
                tvBtnFive.setTextColor(Color.parseColor("#7f3037"));
            }else{

                llBtnFour.setBackgroundResource(R.drawable.bg_tag_gray_dark);
                tvBtnFour.setTextColor(Color.parseColor("#7f3037"));

                llBtnFive.setBackgroundResource(R.drawable.cycle_red_night);
                tvBtnFive.setTextColor(Color.parseColor("#ffffff"));
            }
        }else {
            if (selectIndex == 0) {
                llBtnFour.setBackgroundResource(R.drawable.cycle_red);
                tvBtnFour.setTextColor(Color.parseColor("#ffffff"));

                llBtnFive.setBackgroundResource(R.drawable.bg_tag_gray);
                tvBtnFive.setTextColor(ContextCompat.getColor(context,R.color.text_color_6C788A));
            }else{

                llBtnFour.setBackgroundResource(R.drawable.bg_tag_gray);
                tvBtnFour.setTextColor(ContextCompat.getColor(context,R.color.text_color_6C788A));

                llBtnFive.setBackgroundResource(R.drawable.cycle_red);
                tvBtnFive.setTextColor(Color.parseColor("#ffffff"));
            }
        }
    }

    private void selectTopThreeSelect(int selectIndex) {
        if(WeMediaApplication.getInstance().isDayNightMode_Night){
            if (selectIndex == 0) {
                llBtnOne.setBackgroundResource(R.drawable.cycle_red_night);
                tvBtnOne.setTextColor(Color.parseColor("#ffffff"));

                llBtnTwo.setBackgroundResource(R.drawable.bg_tag_gray_dark);
                tvBtnTwo.setTextColor(Color.parseColor("#7f3037"));

                llBtnThree.setBackgroundResource(R.drawable.bg_tag_gray_dark);
                tvBtnThree.setTextColor(Color.parseColor("#7f3037"));
            } else if (selectIndex == 1) {
                llBtnOne.setBackgroundResource(R.drawable.bg_tag_gray_dark);
                tvBtnOne.setTextColor(Color.parseColor("#7f3037"));

                llBtnTwo.setBackgroundResource(R.drawable.cycle_red_night);
                tvBtnTwo.setTextColor(Color.parseColor("#ffffff"));

                llBtnThree.setBackgroundResource(R.drawable.bg_tag_gray_dark);
                tvBtnThree.setTextColor(Color.parseColor("#7f3037"));
            } else {

                llBtnOne.setBackgroundResource(R.drawable.bg_tag_gray_dark);
                tvBtnOne.setTextColor(Color.parseColor("#7f3037"));

                llBtnTwo.setBackgroundResource(R.drawable.bg_tag_gray_dark);
                tvBtnTwo.setTextColor(Color.parseColor("#7f3037"));

                llBtnThree.setBackgroundResource(R.drawable.cycle_red_night);
                tvBtnThree.setTextColor(Color.parseColor("#ffffff"));
            }
        }else {
            if (selectIndex == 0) {
                llBtnOne.setBackgroundResource(R.drawable.cycle_red);
                tvBtnOne.setTextColor(Color.parseColor("#ffffff"));

                llBtnTwo.setBackgroundResource(R.drawable.bg_tag_gray);
                tvBtnTwo.setTextColor(ContextCompat.getColor(context,R.color.text_color_6C788A));

                llBtnThree.setBackgroundResource(R.drawable.bg_tag_gray);
                tvBtnThree.setTextColor(ContextCompat.getColor(context,R.color.text_color_6C788A));
            } else if (selectIndex == 1) {
                llBtnOne.setBackgroundResource(R.drawable.bg_tag_gray);
                tvBtnOne.setTextColor(ContextCompat.getColor(context,R.color.text_color_6C788A));

                llBtnTwo.setBackgroundResource(R.drawable.cycle_red);
                tvBtnTwo.setTextColor(Color.parseColor("#ffffff"));

                llBtnThree.setBackgroundResource(R.drawable.bg_tag_gray);
                tvBtnThree.setTextColor(ContextCompat.getColor(context,R.color.text_color_6C788A));
            } else {

                llBtnOne.setBackgroundResource(R.drawable.bg_tag_gray);
                tvBtnOne.setTextColor(ContextCompat.getColor(context,R.color.text_color_6C788A));

                llBtnTwo.setBackgroundResource(R.drawable.bg_tag_gray);
                tvBtnTwo.setTextColor(ContextCompat.getColor(context,R.color.text_color_6C788A));

                llBtnThree.setBackgroundResource(R.drawable.cycle_red);
                tvBtnThree.setTextColor(Color.parseColor("#ffffff"));
            }
        }
    }


    private void replaceData() {
        if (isHasTopTitle) {
            if (selectAlbumInfo != null && !TextUtils.isEmpty(selectAlbumInfo.getName())) {
                if (cache != null ) {
                    //清楚缓存数据
                    cache.remove(selectAlbumInfo.getName());
                }
                //请求新的数据
                switchData(selectAlbumInfo);
            }
        }else{
            ApiClient.getInstance().setUseCache(false).getService()
                    .getVipTopic(moreUrl)
                    .compose(RxJavaHelper.<VipTopicGsonBean>observeOnMainThread((Activity) context))
                    .subscribe(new BaseSubscriber<VipTopicGsonBean>(){
                        @Override
                        public void onError(Throwable e) {
                            super.onError(e);
                            setContent(new ArrayList<VipMixWorksBean>());
                        }

                        @Override
                        public void onNext(VipTopicGsonBean bean) {
                            super.onNext(bean);
                            if (bean.getData() != null && bean.getData().getList() != null) {
                                setContent(formatContent(bean.getData().getList()));
                            }else{
                                setContent(new ArrayList<VipMixWorksBean>());
                            }
                        }
                    });
        }
    }


    private void switchData(final VipAlbumBean.AlbumInfo albumInfo) {
        selectAlbumInfo = albumInfo;
        //取缓存数据
        if (cache != null && cache.containsKey(albumInfo.getName())) {
            List<VipMixWorksBean> list = cache.get(albumInfo.getName());
            if (list != null && list.size() > 0) {
                setContent(list);
                return;
            }
        }
        ApiClient.getInstance().setUseCache(false).getService()
                .getVipTopic(albumInfo.getUrl())
                .compose(RxJavaHelper.<VipTopicGsonBean>observeOnMainThread((Activity) context))
                .subscribe(new BaseSubscriber<VipTopicGsonBean>(){
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        setContent(new ArrayList<VipMixWorksBean>());
                    }

                    @Override
                    public void onNext(VipTopicGsonBean bean) {
                        super.onNext(bean);
                        if (bean.getData() != null && bean.getData().getList() != null) {
                            setContent(formatContent(bean.getData().getList()));
                            cache.put(albumInfo.getName(), bean.getData().getList());
                        }else{
                            setContent(new ArrayList<VipMixWorksBean>());
                        }
                    }
                });
    }



    private List<VipMixWorksBean> formatContent(List<VipMixWorksBean> list) {
        return list.subList(0, list.size() > MAX_COUNT ? MAX_COUNT : list.size());
    }


    private void setContent(List<VipMixWorksBean> list) {
        if (contentAdapter != null) {
            contentAdapter.refrush(list);
        }else{
            contentAdapter = new VipNomalGridAdapter(getContext(), list,type,sexType,title,eventBean);
            if (type == DFMemberAdapter.TYPE_VERTICAL) {
                MeasuredLinearLayoutManager manager = new MeasuredLinearLayoutManager(context);
                manager.setOrientation(LinearLayoutManager.VERTICAL);
                manager.setScrollEnabled(false);
                DividerLine dividerLine = new DividerLine(DividerLine.HORIZONTAL);
                dividerLine.setSize(1);
                dividerLine.setColor(R.color.light_gray_color);
                rvContent.addItemDecoration(dividerLine);
                rvContent.setLayoutManager(manager);
            } else if (type == DFMemberAdapter.TYPE_HORIZONTAL) {
                MeasuredLinearLayoutManager manager = new MeasuredLinearLayoutManager(context);
                manager.setOrientation(LinearLayoutManager.HORIZONTAL);
                manager.setScrollEnabled(false);
                rvContent.setLayoutManager(manager);
            }else{
                MeasuredGridLayoutManager gridLayoutManager = new MeasuredGridLayoutManager(getContext(),4);
                gridLayoutManager.setScrollEnabled(false);
                rvContent.setLayoutManager(gridLayoutManager);
            }
            rvContent.setAdapter(contentAdapter);
        }
    }


    public void changeDayModelBg(){
        if(WeMediaApplication.getInstance().isDayNightMode_Night){
            darkBg();
        }else {
            dayBg();
        }
    }


    private void dayBg() {
        root_layout.setBackgroundColor(context.getResources().getColor(R.color.home_list_item_color));
        linearLayout0.setBackgroundColor(context.getResources().getColor(R.color.white));
        tvTitle.setTextColor(context.getResources().getColor(R.color.text_color_1));
        rl_dfnovel_layout1.setBackgroundColor(context.getResources().getColor(R.color.white));

    }

    private void darkBg() {
        root_layout.setBackgroundColor(context.getResources().getColor(R.color.bg_dark));
        linearLayout0.setBackgroundColor(context.getResources().getColor(R.color.fg_dark));
        tvTitle.setTextColor(context.getResources().getColor(R.color.title_text_dark));
        rl_dfnovel_layout1.setBackgroundColor(context.getResources().getColor(R.color.fg_dark));

    }

}
